// 预算管理组件

class BudgetsComponent {
    constructor() {
        this.init();
    }
    
    init() {
        // 初始化预算页面
        this.initBudgetsPage();
    }
    
    // 初始化预算页面
    initBudgetsPage() {
        // 绑定事件
        this.bindEvents();
        
        // 加载预算数据
        this.loadBudgets();
    }
    
    bindEvents() {
        // 新建预算按钮
        const newBudgetBtn = document.querySelector('#budgetsPage #newBudgetBtn');
        if (newBudgetBtn) {
            newBudgetBtn.addEventListener('click', (e) => this.showNewBudgetForm(e));
        }
        
        // 预算表单提交事件
        const budgetForm = document.querySelector('#budgetsPage #budgetForm');
        if (budgetForm) {
            budgetForm.addEventListener('submit', (e) => this.handleBudgetSubmit(e));
        }
        
        // 关闭表单按钮
        const closeFormBtn = document.querySelector('#budgetsPage #closeBudgetForm');
        if (closeFormBtn) {
            closeFormBtn.addEventListener('click', (e) => this.hideBudgetForm(e));
        }
    }
    
    // 显示新建预算表单
    showNewBudgetForm(e) {
        e.preventDefault();
        
        const formContainer = document.querySelector('#budgetsPage .budget-form-container');
        if (formContainer) {
            formContainer.style.display = 'block';
            
            // 重置表单
            const budgetForm = document.querySelector('#budgetsPage #budgetForm');
            if (budgetForm) {
                budgetForm.reset();
                // 设置表单为新建模式
                const budgetIdInput = document.querySelector('#budgetsPage #budgetId');
                if (budgetIdInput) {
                    budgetIdInput.value = '';
                }
            }
        }
    }
    
    // 隐藏预算表单
    hideBudgetForm(e) {
        e.preventDefault();
        
        const formContainer = document.querySelector('#budgetsPage .budget-form-container');
        if (formContainer) {
            formContainer.style.display = 'none';
        }
    }
    
    // 处理预算提交
    async handleBudgetSubmit(e) {
        e.preventDefault();
        
        const formData = new FormData(e.target);
        const budgetData = {
            category_id: formData.get('categoryId'),
            amount: parseFloat(formData.get('amount')),
            period: formData.get('period')
        };
        
        const budgetId = formData.get('budgetId');
        
        // 验证数据
        if (!budgetData.category_id || !budgetData.amount || !budgetData.period) {
            this.showMessage('请填写所有必填字段', 'error');
            return;
        }
        
        try {
            const token = localStorage.getItem('authToken');
            
            // 显示加载状态
            this.setLoading(true);
            
            let response;
            if (budgetId) {
                // 更新预算
                response = await fetch(`http://localhost:3003/api/budgets/${budgetId}`, {
                    method: 'PUT',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${token}`
                    },
                    body: JSON.stringify(budgetData)
                });
            } else {
                // 创建预算
                response = await fetch('http://localhost:3003/api/budgets', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${token}`
                    },
                    body: JSON.stringify(budgetData)
                });
            }
            
            const data = await response.json();
            
            if (response.ok) {
                this.showMessage(budgetId ? '预算更新成功' : '预算创建成功', 'success');
                // 隐藏表单
                this.hideBudgetForm(e);
                // 刷新预算列表
                this.loadBudgets();
            } else {
                this.showMessage(data.error || '操作失败', 'error');
            }
        } catch (error) {
            this.showMessage('网络错误，请稍后重试', 'error');
            console.error('Budget submit error:', error);
        } finally {
            // 恢复按钮状态
            this.setLoading(false);
        }
    }
    
    // 加载预算数据
    async loadBudgets() {
        try {
            const token = localStorage.getItem('authToken');
            
            // 显示加载状态
            this.showLoadingIndicator(true);
            
            // 调用后端API
            const response = await fetch('http://localhost:3003/api/budgets', {
                method: 'GET',
                headers: {
                    'Authorization': `Bearer ${token}`
                }
            });
            
            const data = await response.json();
            
            if (response.ok) {
                // 传递 budgets 数组而不是整个 data 对象
                this.renderBudgets(data.budgets);
            } else {
                this.showMessage(data.error || '加载预算失败', 'error');
            }
        } catch (error) {
            this.showMessage('网络错误，请稍后重试', 'error');
            console.error('Load budgets error:', error);
        } finally {
            // 隐藏加载状态
            this.showLoadingIndicator(false);
        }
    }
    
    // 渲染预算列表
    renderBudgets(budgets) {
        const budgetsContainer = document.querySelector('#budgetsPage .budgets-list');
        if (!budgetsContainer) return;
        
        if (!budgets || budgets.length === 0) {
            budgetsContainer.innerHTML = '<p class="no-data">暂无预算数据</p>';
            return;
        }
        
        let budgetsHTML = '';
        budgets.forEach(budget => {
            // 计算使用百分比
            const percentage = budget.used_amount && budget.amount ? 
                (budget.used_amount / budget.amount) * 100 : 0;
            
            // 判断是否超支
            const isOverBudget = budget.used_amount > budget.amount;
            
            budgetsHTML += `
                <div class="card ${isOverBudget ? 'neon-accent' : ''}">
                    <div style="display: flex; justify-content: space-between; align-items: center;">
                        <div>
                            <h3>${budget.category_name}</h3>
                            <p>预算: ¥${budget.amount.toFixed(2)}</p>
                        </div>
                        <div style="text-align: right;">
                            <p>已用: ¥${(budget.used_amount || 0).toFixed(2)}</p>
                            <p style="color: ${isOverBudget ? 'var(--accent-color)' : 'var(--primary-color)'};">
                                ${percentage.toFixed(1)}%
                            </p>
                        </div>
                    </div>
                    <div style="margin-top: 10px; height: 10px; background: rgba(255, 255, 255, 0.1); border-radius: 5px; overflow: hidden;">
                        <div style="width: ${Math.min(percentage, 100)}%; height: 100%; background: ${isOverBudget ? 'var(--accent-color)' : 'var(--primary-color)'};"></div>
                    </div>
                    <div style="margin-top: 15px; text-align: right;">
                        <button class="btn btn-small" onclick="budgetsComponent.editBudget(${budget.id})">编辑</button>
                        <button class="btn btn-small btn-accent" onclick="budgetsComponent.deleteBudget(${budget.id})">删除</button>
                    </div>
                </div>
            `;
        });
        
        budgetsContainer.innerHTML = budgetsHTML;
    }
    
    // 编辑预算
    async editBudget(budgetId) {
        try {
            const token = localStorage.getItem('authToken');
            
            // 调用后端API获取预算详情
            const response = await fetch(`http://localhost:3003/api/budgets/${budgetId}`, {
                method: 'GET',
                headers: {
                    'Authorization': `Bearer ${token}`
                }
            });
            
            const data = await response.json();
            
            if (response.ok) {
                // 填充表单数据
                const budgetForm = document.querySelector('#budgetsPage #budgetForm');
                if (budgetForm) {
                    document.querySelector('#budgetsPage #budgetId').value = data.id;
                    document.querySelector('#budgetsPage #categoryId').value = data.category_id;
                    document.querySelector('#budgetsPage #amount').value = data.amount;
                    document.querySelector('#budgetsPage #period').value = data.period;
                }
                
                // 显示表单
                const formContainer = document.querySelector('#budgetsPage .budget-form-container');
                if (formContainer) {
                    formContainer.style.display = 'block';
                }
            } else {
                this.showMessage(data.error || '加载预算详情失败', 'error');
            }
        } catch (error) {
            this.showMessage('网络错误，请稍后重试', 'error');
            console.error('Edit budget error:', error);
        }
    }
    
    // 删除预算
    async deleteBudget(budgetId) {
        if (!confirm('确定要删除这个预算吗？')) {
            return;
        }
        
        try {
            const token = localStorage.getItem('authToken');
            
            // 调用后端API
            const response = await fetch(`http://localhost:3003/api/budgets/${budgetId}`, {
                method: 'DELETE',
                headers: {
                    'Authorization': `Bearer ${token}`
                }
            });
            
            if (response.ok) {
                this.showMessage('删除成功', 'success');
                // 刷新预算列表
                this.loadBudgets();
            } else {
                const data = await response.json();
                this.showMessage(data.error || '删除失败', 'error');
            }
        } catch (error) {
            this.showMessage('网络错误，请稍后重试', 'error');
            console.error('Delete budget error:', error);
        }
    }
    
    // 设置加载状态
    setLoading(loading) {
        const submitButton = document.querySelector('#budgetsPage #budgetForm button[type="submit"]');
        if (submitButton) {
            if (loading) {
                submitButton.disabled = true;
                submitButton.textContent = '处理中...';
            } else {
                submitButton.disabled = false;
                submitButton.textContent = '保存';
            }
        }
    }
    
    // 显示/隐藏加载指示器
    showLoadingIndicator(show) {
        const loadingIndicator = document.querySelector('#budgetsPage .loading-indicator');
        if (loadingIndicator) {
            loadingIndicator.style.display = show ? 'block' : 'none';
        }
    }
    
    // 显示消息
    showMessage(message, type) {
        // 创建消息元素
        const messageEl = document.createElement('div');
        messageEl.className = `message message-${type}`;
        messageEl.textContent = message;
        
        // 添加样式
        Object.assign(messageEl.style, {
            position: 'fixed',
            top: '20px',
            right: '20px',
            padding: '15px 20px',
            borderRadius: '5px',
            color: 'white',
            fontWeight: 'bold',
            zIndex: '1000',
            boxShadow: '0 2px 10px rgba(0,0,0,0.3)',
            transition: 'opacity 0.3s'
        });
        
        if (type === 'success') {
            messageEl.style.backgroundColor = '#4CAF50';
        } else if (type === 'info') {
            messageEl.style.backgroundColor = '#2196F3';
        } else {
            messageEl.style.backgroundColor = '#F44336';
        }
        
        // 添加到页面
        document.body.appendChild(messageEl);
        
        // 3秒后淡出并移除
        setTimeout(() => {
            messageEl.style.opacity = '0';
            setTimeout(() => {
                if (messageEl.parentNode) {
                    messageEl.parentNode.removeChild(messageEl);
                }
            }, 300);
        }, 3000);
    }
}

// 初始化预算组件
document.addEventListener('DOMContentLoaded', () => {
    window.budgetsComponent = new BudgetsComponent();
});